package com.baichang.taoshunda.dao.impl;

import com.baichang.framework.dao.impl.BaseDaoImpl;
import com.baichang.framework.excelption.DBException;
import com.baichang.framework.model.Page;
import com.baichang.taoshunda.dao.UserDao;
import com.baichang.taoshunda.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

    /**
     * 根据用户名获取用户
     * 接口
     *
     * @param userName 用户名
     * @return 用户
     */
    @Override
    public User getUserByUserName(String userName) {
        String sql = " SELECT * FROM `t_user` WHERE account=? AND user_state!=0";
        return queryForBean(sql, userName);
    }

    /**
     * 根据用户id
     * 修改密码
     *
     * @param id  用户id
     * @param pwd 密码
     * @return 修改成功/失败
     */
    @Override
    public int updateUserPwd(Integer id, String pwd) {
        String sql = " UPDATE {table} SET pwd=? WHERE id=? ";
        return update(sql, pwd, id);
    }


    /**
     * 接口
     * 根据用户编号获取用户
     *
     * @param userId 用户编号
     * @return 用户
     */
    @Override
    public User getUserByUserId(Integer userId) {
        String sql = " SELECT * FROM {table} WHERE id=? AND user_state=1 ";
        return queryForBean(sql, userId);
    }


    /**
     * 接口
     * 修改个人信息
     *
     * @param id      用户编号
     * @param headPic 头像
     * @param name    名称
     * @param sex
     * @return 修改成功/失败
     */
    @Override
    public int updateUserInfo(Integer id, String headPic, String name, String sex) {
        String sql = " UPDATE {table} SET nick_name=?,head_pic=?,sex=? WHERE id=? ";
        return update(sql, name, headPic, sex, id);
    }

    /**
     * 查询用户列表
     *
     * @param nowPage
     * @param pageSize
     * @param nickName
     * @param startCreate
     * @param endCreate   @return
     * @param startTime
     * @param endTime
     */
    @Override
    public Page queryUserList(int nowPage, int pageSize, String nickName, String startCreate, String endCreate, String startTime, String endTime) {
        List list = new ArrayList();
        String sql = "SELECT u.* , ( SELECT COUNT(0) FROM t_bussiness WHERE u.id = user_id ) AS companyNumber, IFNULL(( SELECT SUM(rebate_amount) FROM t_rebate_amount WHERE user_id = u.id ), 0) AS allRebateAmount , IFNULL(( SELECT SUM(o.all_money) FROM t_rebate_amount ra INNER JOIN t_order o ON o.order_number = ra.order_number WHERE user_id = u.id ), 0) AS goodsAllMoney , TIMESTAMPDIFF(YEAR, u.created, NOW()) AS yearNumber , TIMESTAMPDIFF(MONTH, u.created, NOW()) % 12 AS monthNumber FROM t_user u WHERE u.user_state IN (1, 2) ";
        if (StringUtils.isNotBlank(nickName)) {
            sql += " AND u.nick_name LIKE ?";
            list.add("%" + nickName + "%");
        }
        if (!startCreate.equals("") && !endCreate.equals("")) {
            sql += " AND u.created>=? AND u.created <=DATE_ADD(?, Interval 1 DAY)";
            list.add(startCreate);
            list.add(endCreate);
        }
        if (!startTime.equals("") && !endTime.equals("")) {
            sql += " AND u.last_time>=? AND u.last_time<=DATE_ADD(?, Interval 1 DAY)";
            list.add(startTime);
            list.add(endTime);
        }
        sql += " ORDER BY created DESC ";
        return pageForMapList(sql, nowPage, pageSize, list.toArray());
    }

    /**
     * 修改用户信息
     *
     * @param map
     * @param id
     * @return
     */
    @Override
    public int update(Map map, Integer id) {
        String sql = "id=?";
        return update(sql, map, id);
    }

    /**
     * 重置密码
     *
     * @param id
     * @param pass
     * @return
     */
    @Override
    public int updatePassWord(Integer id, String pass) {
        String sql = "UPDATE t_user SET pwd=? WHERE id=?";
        return update(sql, pass, id);
    }

    /**
     * 修改用户状态
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateUserState(Integer id, Integer state) {
        String sql = "UPDATE t_user SET user_state=? WHERE id=?";
        return update(sql, state, id);
    }

    @Override
    public boolean updateUserLastTime(long userId, Date date) throws DBException {
        String sql = "update {table} set last_time=? where id=?";
        return update(sql, date, userId) == 1;
    }

    /**
     * 换绑手机号
     *
     * @param userName 手机号
     * @param userId   用户编号
     * @return
     */
    @Override
    public boolean changePhone(String userName, int userId) {
        String sql = "UPDATE `t_user` SET `account`=? WHERE (`id`=?)";
        return update(sql, userName, userId) > 0;
    }

    @Override
    public Map<String, Object> getUserInfoByTrendsUserId(int userId) {
        String sql = "SELECT IFNULL(us.id, bu.id) id, IFNULL(us.nick_name, bu.buss_name) `name`, IFNULL(us.head_pic, bu.head_pic) headPicpath, IFNULL(us.account, bu.account) account, CASE ISNULL(us.id) WHEN 1 THEN 2 WHEN 0 THEN 1 END AS type FROM t_trends_user tu LEFT JOIN t_user us ON tu.user_id = us.id LEFT JOIN t_bussiness bu ON tu.bus_id = bu.id WHERE tu.id=?";
        return queryForMap(sql, userId);
    }

    @Override
    public boolean updateHxuserInfo(Integer userId, String emId, Object emPwd) {
        String sql = "UPDATE `t_user` SET `hx_name`=?, `hx_pwd`=? WHERE id=?";
        return update(sql, emId, emPwd, userId) > 0;
    }

    @Override
    public void updateRYToken(String ryToken, Integer userId, String trendsUserId) {
        String sql = "update {table} SET ry_token=?,trends_user_id=? WHERE id=?";
        update(sql, ryToken, trendsUserId, userId);
    }

    @Override
    public boolean updatebackgroundImage(String backGroundImage, Integer userId) {
        String sql = "UPDATE `t_user` SET `background_image`=? WHERE (`id`=? )";
        return update(sql, backGroundImage, userId) > 0;
    }

    /**
     * @return
     */
    @Override
    public Map<String, Object> userCount() {
        String sql = "SELECT COUNT(*) AS userCount FROM t_user WHERE user_state=1";
        return queryForMap(sql);
    }

    /**
     * 功能描述:
     * 用户实名认证
     *
     * @param userId         用户编号
     * @param cardId         身份证号
     * @param cardName       身份证上的姓名
     * @param handheldPhotos 手持身份证照片
     * @param fontCard       身份证正面
     * @param reverseCard    身份证反面
     * @return:
     * @auther: wsl
     * @date: 2018/11/29 15:52
     */
    @Override
    public boolean certification(int userId, String cardId, String cardName, String handheldPhotos, String fontCard, String reverseCard) {
        String sql = "UPDATE t_user SET card_id=?,card_name=?,handheld_photos=?,is_certification=1,font_card=?,reverse_card=? WHERE id=?";
        return update(sql, cardId, cardName, handheldPhotos, fontCard, reverseCard, userId) > 0;
    }

    @Override
    public boolean updateIsCertification(Integer id, Integer type) {
        String sql = "UPDATE `t_user` ";

        if (type == 1) {
            sql += "  SET `is_certification`='1', `is_certificate`='1' ";
        } else {
            sql += " SET `is_certification`='0', `is_certificate`='0' ";
        }
        sql += " WHERE (`id`=?)";
        return update(sql, id) > 0;
    }

    /**
     * 功能描述:
     * 查询用户的关联商家
     *
     * @param id       用户编号
     * @param nowPage  当前页
     * @param pageSize 每页条数
     * @return:
     * @auther: wsl
     * @date: 2019/1/12 10:04
     */
    @Override
    public Page queryCompanyList(Integer id, int nowPage, int pageSize) {
        String sql = "SELECT b.id, b.account, b.created, b.buss_name AS bussName, b.user_id AS userId , ( SELECT COUNT(id) FROM t_rebate_amount WHERE company_id = b.id ) AS orderNumber, IFNULL(( SELECT SUM(rebate_amount) FROM t_rebate_amount WHERE company_id = b.id ), 0) AS allRebateAmount , IFNULL(( SELECT SUM(o.all_money) FROM t_rebate_amount ra INNER JOIN t_order o ON o.order_number = ra.order_number WHERE company_id = b.id ), 0) AS goodsAllMoney FROM t_bussiness b WHERE b.user_id = ? ORDER BY b.id DESC";
        return pageForMapList(sql, nowPage, pageSize, id);
    }

    @Override
    public void updateInviteAccount(int userId, String phone) {
        String sql = "UPDATE `t_user` SET `invite_account`=? WHERE (`id`=? )";
        update(sql, phone, userId);
    }


}